<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">            
        <el-form-item label="账单用途">
          <el-select clearable placeholder="账单用途" v-model="searchInfo.billUseFor">
            <el-option :key="item" :label="item" :value="item" v-for="item in billUseForList"></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="操作人">
          <el-select clearable placeholder="操作人" v-model="searchInfo.billOperator">
            <el-option :key="item.label" :label="`${item.label}(${item.value})`" :value="item.label" v-for="item in userOptions"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item>
          <el-button @click="onSubmit" type="primary" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="openDialog" type="primary" icon="el-icon-plus">新增财务单</el-button>
        </el-form-item>
        <el-form-item>
          <el-popover placement="top" v-model="deleteVisible" width="160">
            <p>确定要删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button @click="deleteVisible = false" size="mini" type="text">取消</el-button>
                <el-button @click="onDelete" size="mini" type="primary">确定</el-button>
              </div>
            <el-button icon="el-icon-delete" slot="reference" type="danger">批量删除</el-button>
          </el-popover>
        </el-form-item>

      </el-form>
    </div>
    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      border
      show-summary
      ref="multipleTable"
      stripe
      style="width: 100%"
      tooltip-effect="dark"
      :default-sort = "{prop: 'billId', order: 'descending'}"
    >
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column label="日期" width="180">
         <template slot-scope="scope">{{scope.row.CreatedAt|formatDate}}</template>
    </el-table-column>
    
    <el-table-column label="账单ID" prop="billId" width="80"></el-table-column> 
    
    <el-table-column label="用途" prop="billUseFor" width="100"></el-table-column> 
    
    <el-table-column label="金额" prop="billAmount" width="80"></el-table-column> 

    <!-- <el-table-column label="关联进货单" prop="billRelateGoodsOrder" width="120"></el-table-column>  -->
    
    <el-table-column label="操作人" prop="billOperator" width="100"></el-table-column> 
    
    <el-table-column label="确认人" prop="billConfirm" width="100"></el-table-column> 

    <el-table-column label="备注" prop="billRemarks" width="400"></el-table-column> 
    
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button class="table-button" @click="confirmBill(scope.row)" size="small" type="primary" icon="el-icon-edit">确认</el-button>
          <el-button class="table-button" @click="updateBillList(scope.row)" size="small" type="primary" icon="el-icon-edit">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog :before-close="closeDialog" :visible.sync="dialogFormVisible" title="新增财务单">
      <el-form :model="formData" label-position="right" label-width="120px">
         <!-- <el-form-item label="账单ID:"><el-input v-model.number="formData.billId" clearable placeholder="请输入"></el-input>
      </el-form-item> -->
       
      <el-form-item label="支出用途">
          <el-select clearable placeholder="请选择" v-model="formData.billUseFor">
            <el-option :key="item" :label="item" :value="item" v-for="item in billUseForList"></el-option>
          </el-select>
      </el-form-item>       
       
      <el-form-item label="金额">
              <el-input-number v-model="formData.billAmount" :precision="2" clearable></el-input-number>
       </el-form-item>
       <el-form-item label="备注信息">
                <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="formData.billRemarks"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="enterDialog">立即创建</el-button>
            <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
       </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
    createBillList,
    deleteBillList,
    deleteBillListByIds,
    updateBillList,
    findBillList,
    getBillListList,
    confirmBill
} from "@/api/billList";  //  此处请自行替换地址
import { formatTimeToStr } from "@/utils/date";
import infoList from "@/mixins/infoList";
import {getUserList} from "@/api/user";
import {
    createGoodsOrder,
    deleteGoodsOrder,
    deleteGoodsOrderByIds,
    updateGoodsOrder,
    findGoodsOrder,
    getGoodsOrderList
} from "@/api/goodsOrder";  //  此处请自行替换地址
export default {
  name: "BillList",
  mixins: [infoList],
  data() {
    return {
      listApi: getBillListList,
      dialogFormVisible: false,
      type: "",
      deleteVisible: false,
      multipleSelection: [],
      formData: {
            billId:0,
            billUseFor:"",
            billRelateGoodsOrder:"",
            billOperator:"",
            billConfirm:"",
            billAmount:0,
            BillRemarks:""
      },
      userOptions:[],
      billUseForList: ["进货", "店铺运营", "打样", "物流", "其他"],
      goodsOrderList: []
    };
  },
  filters: {
    formatDate: function(time) {
      if (time != null && time != "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
      } else {
        return "";
      }
    },
    formatBoolean: function(bool) {
      if (bool != null) {
        return bool ? "是" :"否";
      } else {
        return "";
      }
    },
    // 日元换算人民币
    convertJPY2RMB: function(jpy){
      const exchangeRate = 6
      return (Number(jpy) * exchangeRate) / 100
    },
    convertRMB2JPY: function(rmb){
      const exchangeRate = 6
      return (Number(rmb) / exchangeRate) * 100
    },
  },
  methods: {
      //条件搜索前端看此方法
      onSubmit() {
        this.page = 1
        this.pageSize = 10          
        this.getTableData()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      deleteRow(row){
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.deleteBillList(row);
        });
      },
      async onDelete() {
        const ids = []
        if(this.multipleSelection.length == 0){
          this.$message({
            type: 'warning',
            message: '请选择要删除的数据'
          })
          return
        }
        const isDelete = true
        this.multipleSelection &&
          this.multipleSelection.map(item => {
            if(item.billConfirm != ""){
              this.$message({
                type: "warning",
                message: "确认过的账单，禁止删除！"
              })
              isDelete = false
            }
            ids.push(item.ID)
          })
        if(isDelete){
          const res = await deleteBillListByIds({ ids })
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            if (this.tableData.length == ids.length) {
                this.page--;
            }
            this.deleteVisible = false
            this.getTableData()
          }
        } 
        
      },
    async updateBillList(row) {
      const res = await findBillList({ ID: row.ID });
      this.type = "update";
      if (res.code == 0) {
        this.formData = res.data.rebillList;
        this.dialogFormVisible = true;
      }
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.formData = {
          billId:0,
          billUseFor:"",
          billRelateGoodsOrder:"",
          billOperator:"",
          billConfirm:"",
          billAmount:0,
          
      };
    },
    async deleteBillList(row) {
      const res = await deleteBillList({ ID: row.ID });
      if (res.code == 0) {
        this.$message({
          type: "success",
          message: "删除成功"
        });
        if (this.tableData.length == 1) {
            this.page--;
        }
        this.getTableData();
      }
    },
    async enterDialog() {
      let res;
      switch (this.type) {
        case "create":
          res = await createBillList(this.formData);
          break;
        case "update":
          res = await updateBillList(this.formData);
          break;
        default:
          res = await createBillList(this.formData);
          break;
      }
      if (res.code == 0) {
        this.$message({
          type:"success",
          message:"创建/更改成功"
        })
        this.closeDialog();
        this.getTableData();
      }
    },
    openDialog() {
      this.type = "create";
      this.dialogFormVisible = true;
    },
    confirmBill(row){
      this.$confirm('确认后将永久不能删除, 是否继续?', '谨慎操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.confirmBillYes(row);
      });
    },
    async confirmBillYes(row){
      if(row.billConfirm != ""){
        this.$message({
          type:"warning",
          message:"已确认，无需重复操作！"
        })
      }else{
        let res;
        res = await confirmBill(row);
        if (res.code == 0) {
          this.$message({
              type: 'success',
              message: "确认成功"
          });
          this.getTableData();
        }
      }
    },
    async initUserList(){
      const res =  await getUserList({ page:1, pageSize:9999});
      if(res.code == 0){
        res.data.list.forEach(element => {
          this.userOptions.push({
            "label": element.nickName,
            "value": element.userName
          })
        });
      }
    },
  },
  created() {
    this.initUserList();
    this.getTableData();
}
};
</script>


<style scoped lang="scss">
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  .el-tag--mini {
    margin-left: 5px;
  }
  .warning {
    color: #dc143c;
  }
</style>
<style>
  .el-select .el-input {
    width: 170px;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .transfer-footer {
    margin-left: 20px;
    padding: 6px 5px;
  }
  .admin-box .el-input__inner {
    height: 35px;
    line-height: 30px;
  }
</style>